package com.skaz.security;

import com.skaz.util.Servlets;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: jungle
 * @Date: 2018/11/7 3:56 PM
 */
public class SecurityFilter extends AbstractAuthenticationProcessingFilter {


    private final SecurityManager securityManager;

    public SecurityFilter(SecurityManager securityManager, AuthenticationManager authenticationManager) {
        super(AnyRequestMatcher.INSTANCE);
        setAuthenticationManager(authenticationManager);
        this.securityManager = securityManager;
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        if (!this.requiresAuthentication(request, response)) {
            chain.doFilter(request, response);
        } else {
            String accessToken = request.getHeader(Securitys.AUTHORIZATION_HEADER);
            try {
                if (StringUtils.hasText(accessToken)) {
                    securityManager.filter(accessToken, request);
                }
                chain.doFilter(req, resp);
            } catch (Exception ex) {
                Servlets.sendFailure(request, response, ex);
            }
        }
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        return null;
    }


}
